define(["angularAMD", "sortablejs"], function (angularAMD, Sortable) {
    angularAMD.service('customOrderService', ['$rootScope', '$filter', '$translate', 'config', '$mdDialog', '$timeout',
            function ($rootScope, $filter, $translate, config, $mdDialog, $timeout) {
                const getSettings = (listName, columns = []) => {
                    // 20240103 modify by wenwei for M#153678: 派工作業 & 多日派工共用排序設定
                    const key = `${ listName }_order_${ config.cache.account }`;
                    const settings = JSON.parse(localStorage.getItem(key)) || [];
                    if(columns.length > 0) {
                        // 更新欄位名稱
                        for(let setting of settings) {
                            const col = columns.find((col) => col.code === setting.code) || {};
                            setting.label = col.label || '';
                        }
                    }
                    return settings;
                }

                // 保存排序設定
                const setSettings = (listName, settings) => {
                    // 清除空白設定，更新排序
                    settings = settings
                        .filter((item) => item.code)
                        .map((item, index) => {
                            item.order = index + 1;
                            return item;
                        });
                    // 20240103 modify by wenwei for M#153678: 派工作業 & 多日派工共用排序設定
                    const key = `${ listName }_order_${ config.cache.account }`;
                    localStorage.setItem(key, JSON.stringify(settings));
                }

                this.init = function (params) {
                    openDialog(params);
                }

                this.getSettings = getSettings;
                this.setSettings = setSettings;

                var openDialog = function (params) {
                    $mdDialog.dialog('module/moduleA/program/B01/custom_order/custom_order.html',
                        function (dialog) {
                            return {
                                settings: getSettings(params.listName, params.columns) ,
                                css_url: 'module/moduleA/program/B01/custom_order/custom_order.css',
                                beforeShown: function() {
                                    Sortable.create($('.custom-order .kmi-list__row-content')[0], {
                                        ghostClass: 'ghost',
                                        filter: '.undragable',
                                        handle: '.sortable-btn',
                                        onEnd: function (evt) {
                                            $timeout(() => { 
                                                // 更新model
                                                dialog.settings.splice(evt.newIndex, 0, dialog.settings.splice(evt.oldIndex, 1)[0]);
                                                dialog.settings = dialog.settings
                                                    .map((item, index) => {
                                                        item.order = index + 1;
                                                        return item;
                                                    });
                                            })
                                        }
                                    });
                                },
                                back: function() {
                                    dialog.hide();
                                },
                                confirm: function() {
                                    dialog.hide();
                                    setSettings(params.listName, dialog.settings);
                                    if(typeof params.callback === 'function') {
                                        // 依據設定刷新未派工清單
                                        params.callback(dialog.settings);
                                    }
                                },
                                changeSort: function(item) {
                                    item.sort = item.sort === 'asc' ? 'desc' : 'asc';
                                },
                                addCol: function() {
                                    dialog.settings.push({
                                        order: dialog.settings.length + 1,
                                        label: '',
                                        code: '',
                                        sort: 'asc'
                                    });
                                },
                                deleteCol: function(index) {
                                    dialog.settings.splice(index, 1);
                                    dialog.settings = dialog.settings
                                        .map((item, index) => {
                                            item.order = index + 1;
                                            return item;
                                        });
                                },
                                selectColumn: function(event, item) {
                                    // 過濾已選擇的欄位
                                    const filtedColumns = params.columns.filter((col) => !dialog.settings.find((setting) => setting.code === col.code));
                                    $rootScope.showSelect({
                                        title: $filter('translate')('common.msg.plz_select'),
                                        label: function(item) {
                                            return item.label || item.code;
                                        },
                                        code: 'code',
                                        list: filtedColumns,
                                        confirm: function (selectedItem, d) {
                                            d.hide();
                                            item.label = selectedItem.label;
                                            item.code = selectedItem.code;
                                        }
                                    });
                                }
                            }
                        });
                };
            }
        ])
    });